package com.whpost.api.controller.stamp;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.whpost.api.controller.BaseController;
import com.whpost.api.utils.ApiUtils;
import com.whpost.service.dao.stamp.StampHdDhmMapper;
import com.whpost.service.entity.stamp.Dhm;
import com.whpost.service.entity.stamp.StampHdDhm;
import com.whpost.service.entity.stamp.StampXm;
import com.whpost.service.entity.tools.ResultInfo;
import com.whpost.service.service.stamp.StampHdDhmServices;
import com.whpost.service.service.stamp.StampXmServices;
import com.whpost.service.tools.ToolBean;
import com.whpost.service.tools.Url;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/stamp/dhm")
public class StampDhmController extends BaseController {

    @Resource
    private StampHdDhmServices stampHdDhmServices;
    @Resource
    private StampHdDhmMapper stampHdDhmMapper;

    @Autowired
    public StampDhmController(StampHdDhmServices stampHdDhmServices) {
        super();
        setPerCode("stampdhm");
        setBaseServices(stampHdDhmServices);
    }

    /**
     * 下载
     * @return
     */
    @RequestMapping(value = "/xz")
    public void xz(String token, String id, HttpServletResponse response) {
        // 禁止默认异常处理器干扰响应流（关键）
        response.setStatus(HttpServletResponse.SC_OK);
        OutputStream os = null;
        try {
            // 1. 权限校验
            StpUtil.checkPermission("stampdhm:query");
            String loginId = (String) StpUtil.getLoginIdByToken(token);
            String ids = "";
            List<Dhm> dhmList = new ArrayList<>();

            // 2. 处理业务逻辑
            try {
                ids = Url.decrypt(id);
            } catch (Exception e) {
                dhmList.add(new Dhm("解密失败：" + e.getMessage()));
            }

            if (StringUtils.isEmpty(ids)) {
                dhmList.add(new Dhm("数据丢失！"));
            } else {
                StampHdDhm stampHdDhm = stampHdDhmMapper.selectById(ids);
                if (stampHdDhm != null) {
                    if (String.valueOf(stampHdDhm.getTCzyId()).equals(loginId)) {
                        dhmList = stampHdDhmMapper.getDhm(ids);
                        // 避免空数据导致Excel生成失败（至少保留表头）
                        if (dhmList == null) {
                            dhmList = new ArrayList<>();
                        }
                    } else {
                        dhmList.add(new Dhm("非自己创建的兑换码无法下载！"));
                    }
                } else {
                    dhmList.add(new Dhm("兑换码明细不存在！"));
                }
            }

            //解码
            for (Dhm dhm : dhmList) {
                String dhm1 = Url.decrypt(dhm.getDhm());
                dhm.setDhm(dhm1);
                String sybz = dhm.getSfsy();
                if ("0".equals(sybz)) dhm.setSfsy("未使用");
                if ("1".equals(sybz)) dhm.setSfsy("已使用");
            }

            // 3. 设置响应头（严格指定.xlsx格式）
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("Dhm数据导出"+ToolBean.getTodayStr("yyyymmddhhmmss"), StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
            response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");
            response.setHeader("Cache-Control", "no-store, no-cache");

            // 4. 生成Excel（确保即使有错误信息，也生成有效的Excel文件）
            os = response.getOutputStream();
            EasyExcel.write(os, Dhm.class)
                    .sheet("数据")
                    .doWrite(dhmList);
            os.flush();

        } catch (Exception e) {
            // 关键：异常时仍生成一个包含错误信息的有效Excel，而非文本
            try {
                if (!response.isCommitted()) {
                    // 重置响应头（确保是Excel格式）
                    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                    response.setCharacterEncoding("utf-8");
                    String fileName = URLEncoder.encode("导出错误", StandardCharsets.UTF_8.name()).replaceAll("\\+", "%20");
                    response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");

                    // 生成包含错误信息的Excel
                    List<Dhm> errorList = new ArrayList<>();
                    errorList.add(new Dhm("导出失败：" + e.getMessage()));
                    os = response.getOutputStream();
                    EasyExcel.write(os, Dhm.class)
                            .sheet("错误信息")
                            .doWrite(errorList);
                    os.flush();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } finally {
            // 关闭流
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            // 强制完成响应，防止后续处理
            try {
                response.flushBuffer();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
